/*
 * @Author: mikey.zhaopeng
 * @Date: 2019-05-01 08:39:14
 * @Last Modified by: mikey.zhaopeng
 * @Last Modified time: 2019-05-01 13:41:15
 */
;(function() {
  'use strict'

  var $form_add_task = $('.add-task'),
    task_list = [],
    $task_list = $('.task-list'),
    $task_detail_mask = $('.task-detail-mask'),
    $task_detail = $('.task-detail'),
    $close = $('.close'),
    current_index,
    $update_from,
    $task_detail_content,
    $task_detail_content_input,
    $task_delete_trigger,
    $task_detail_trigger,
    $checkbox_complete

  init()

  $task_detail_mask.on('click', hide_task_detail)
  $task_detail.on('click', '.close', hide_task_detail)
  // 添加todo项事件
  $form_add_task.on('submit', function(e) {
    e.preventDefault()
    var new_task = {}

    var $input = $(this).find('input[name=content]')
    new_task.content = $input.val().trim()
    if (!new_task.content) return

    if (add_task(new_task)) {
      render_task_list(task_list)
      $input.val('')
    }
  })

  $task_detail.on('submit', function(e) {
    e.preventDefault()
    var $this = $(this)

    var data = {}
    $this.serializeArray().forEach(function(item) {
      data[item.name] = item.value
    })
    update_task(current_index, data)
  })

  // TODO:
  /**
   * 方法绑定在父元素，用了委托机制，不需要每次更新dom后重新渲染
   */
  function listen_task_detail() {
    var index
    $task_list.on('click', '.detail', function(e) {
      e.stopPropagation()
      var $this = $(this)
      index = $this
        .parent()
        .parent()
        .data('index')
      current_index = index
      show_task_detail()
      render_task_detail(index)
    })
    // TODO: 可函数式封装优化代码 双击显示详情
    $task_list.on('dblclick', '.task-item', function() {
      var $this = $(this)
      index = $this.data('index')
      current_index = index
      show_task_detail()
      render_task_detail(index)
    })
  }
  listen_task_detail()

  function listen_task_item_click() {
    $task_list.on('click', '.task-item', function(e) {
      var $this = $(this)
      var index = $this.data('index')
      var item = getItem(index)
      update_task(index, {
        complete: !item.complete
      })
    })
  }
  listen_task_item_click()
  // TODO:
  function listen_task_delete() {
    $task_list.on('click', '.delete', function(e) {
      e.stopPropagation()
      var $this = $(this)
      var index = $this
        .parent()
        .parent()
        .data('index')
      var judge = confirm('确认删除？')
      if (judge) {
        delete_task(index)
        reflush_task_list(task_list)
      }
    })
  }
  listen_task_delete()
  // TODO:
  /**
   * 绑定的元素动态生成，每次更新dom需要重新绑定
   * 所以在更新dom后执行  执行render_task_list()后执行
   */
  function listen_checkbox_complete() {
    $checkbox_complete.on('click', function() {
      var $this = $(this)
      var index = $this.parent().data('index')
      var item = getItem(index)
      update_task(index, {
        complete: !item.complete
      })
    })
  }

  // 显示详情
  function show_task_detail() {
    $task_detail_mask.show()
    $task_detail.show()
  }

  // 隐藏详情
  function hide_task_detail() {
    $task_detail_mask.hide()
    $task_detail.hide()
  }

  // 渲染详情模板
  function render_task_detail(index) {
    if (index === 'undefined' || !task_list[index]) return

    var item = task_list[index]
    var desc = item.desc ? item.desc : ''
    var time = item.remind_date ? item.remind_date : ''

    var content = $.trim(item.content)

    var tpl =
      '<div class="detail-box">' +
      '<a class="close" href="javascript:;">X</a>' +
      '<div class="content">' +
      content +
      '</div>' +
      '<input type="text" class="content" style="display:none;" name="content" autocomplete="off" value="' +
      content +
      '">' +
      '<div class="desc">' +
      '<textarea name="desc">' +
      desc +
      '</textarea>' +
      '</div>' +
      '<div class="remind">' +
      '<input class="datetime" type="text" name="remind_date" autocomplete="off" value="' +
      time +
      '" />' +
      '<button type="submit">更新</button>' +
      '</div>' +
      '</div>'

    $task_detail.empty()
    $task_detail.append(tpl)
    $('.datetime').datetimepicker({
      lang: 'ch',
      theme: 'dark'
    })
    $update_from = $task_detail.find('from')
    $task_detail_content = $task_detail.find('.content')
    $task_detail_content_input = $task_detail.find('input[name=content]')

    // 双击修改标题
    $task_detail_content.on('dblclick', function() {
      $task_detail_content.hide()
      $task_detail_content_input.show()
    })
  }

  // 添加task
  function add_task(new_task) {
    task_list.push(new_task)
    store.set('task_list', task_list)
    return true
  }

  // 删除task
  function delete_task(index) {
    if (index === 'undefined' || task_list[index] == null) return
    delete task_list[index]
    return true
  }

  // 更新task
  function update_task(index, data) {
    if (index === 'undefined' || !task_list[index]) return
    $.extend(task_list[index], data)
    if (reflush_task_list()) {
      // alert('更新成功')
      hide_task_detail()
      return true
    }
  }

  // 刷新task列表
  function reflush_task_list() {
    $task_list.empty()
    store.set('task_list', task_list)
    render_task_list(task_list)
    return true
  }

  // 渲染task列表
  function render_task_list(task_item) {
    $task_list.empty()
    var task = ''
    var complete_item = []
    var complete_html = ''
    for (var i = 0, l = task_item.length; i < l; i++) {
      var descend = l - 1 - i
      var item = task_item[descend]
      if (item && item.complete) {
        complete_item.push(item)
        complete_html += render_task_item(item, descend)
      } else {
        task += render_task_item(item, descend)
      }
    }
    task += complete_html
    $task_list.append(task)

    $task_delete_trigger = $('.action.delete')
    $task_detail_trigger = $('.action.detail')
    $checkbox_complete = $('.task-list .complete')
    listen_checkbox_complete()
    return true
  }

  // 渲染todo项
  function render_task_item(data, index) {
    if (!data || index === 'undefined') return ''
    var list_item_tpl =
      '<div class="task-item' +
      (data.complete ? ' completed' : '') +
      '" data-index="' +
      index +
      '">' +
      '<input class="complete" type="checkbox" name=""' +
      (data.complete ? 'checked="checked"' : '') +
      '>' +
      '<span class="task-content">' +
      data.content +
      '</span>' +
      '<span class="fr">' +
      '<span class="action delete"> 删除</span>' +
      '<span class="action detail"> 详情</span>' +
      '</span>' +
      '</div>'
    return list_item_tpl
  }

  // 获取todo项的对象数据
  function getItem(index) {
    return store.get('task_list')[index]
  }

  function task_remind_check() {
    var current_timestamp
    var timer = setInterval(function() {
      for (var i = 0; i < task_list.length; i++) {
        var item = getItem(i),
          task_timestamp
        if (!item || !item.remind_date) {
          continue
        }
        current_timestamp = new Date().getTime()
        task_timestamp = new Date(item.remind_date).getTime()

        // TODO:
        if (task_timestamp - current_timestamp > 1000) {
          clearInterval(timer)
          notify()
        }
      }
    }, 1000)
  }

  // TODO:
  function notify() {
    console.log('提醒我')
  }

  function init() {
    task_list = store.get('task_list') || []
    if (task_list.length) render_task_list(task_list)
    task_remind_check()
  }
})()
